const app = getApp()
import { getUserInfo, logout, projectIslandLogin } from '../../../api/index'

Page({
  data: {
    userInfo: {
      type: 1
    },
    showAuthor: false
  },
  editApprove () {
    if (this.data.userInfo.applyStatus === 2) {
      wx.showToast({ title: '企业认证审核中，请耐心等待', icon: 'none' })
      return
    }
    wx.$nav.navigateTo(`/pages/account/approve/index`)
  },
  seeUserinfo () {
    if (!this.data.userInfo.userInfo.authorize) {
      this.setData({ showAuthor: true })
    } else {
      wx.$nav.navigateTo(`/pages/account/info/index`)
    }
  },
  async goIsland () {
    try {
      wx.showLoading({ title: '项目岛登陆中...', mask: true })
      await projectIslandLogin()
      wx.showLoading()
      wx.$nav.navigateTo(`/pages/account/island/list/index`)
    } catch (err) {
      wx.showLoading()
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  async logout () {
    try {
      await logout()
      await wx.$pro.removeStorageSync('CNPASS')
      await wx.$pro.removeStorageSync('FIRSTLOGIN')
      wx.$nav.redirectTo(`/pages/login/index`)
    } catch (err) {
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  setting () {
    wx.$nav.navigateTo(`/supplier/pages/setting/index`)
  },
  closeAuthor () {
    this.setData({ showAuthor: false })
    wx.$nav.navigateTo(`/pages/account/info/index`)
  },
  async updateAuthor () {
    await this.getUserInfo()
    await wx.$pro.showToast({ title: '用户信息更新成功！', icon: 'none' })
    this.setData({ showAuthor: false })
    wx.$nav.navigateTo(`/pages/account/info/index`)
  },
  async getUserInfo () {
    try {
      wx.showLoading({ title: '加载中...', mask: true })
      const { ResultSet } = await getUserInfo()
      if (!ResultSet.userData.userInfo || !ResultSet.userData.userInfo.userId) {
        wx.showToast({ title: '用户未登录', icon: 'none' })
        wx.$nav.redirectTo('/pages/login/index')
      } else {
        app.globalData.userInfo = ResultSet.userData.userInfo
        this.setData({
          userInfo: ResultSet.userData
        })
      }
      wx.hideLoading()
    } catch (err) {
      wx.hideLoading()
      console.log(err)
      wx.showToast({ title: err.message || err.ResultSet.errors, icon: 'none' })
    }
  },
  // onLoad () {
  //   const { userInfo } = app.globalData
  //   if (!userInfo || !userInfo.userInfo || !userInfo.userInfo.userId) {
  //     wx.$nav.navigateTo('/pages/login/index')
  //   }
  // },
  onShow () {
    this.getUserInfo()
  }
})
